package com.flower.wholesale.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import com.flower.wholesale.enu.RedisKeyEnum;
import com.flower.wholesale.util.CookiesUtil;
import com.flower.wholesale.util.RedisUtil;

/**
 * @author: 姚雁飞
 * @desc: 用户登录拦截
 * @date: 2020年4月23日 下午4:25:37
 * @since JDK1.8
 * @see com.flower.wholesale.filter
 */
@WebFilter(filterName = "LoginFilter", urlPatterns = { "/*" })
@Order(value = 1)
@Configuration
public class LoginFilter implements Filter {

	private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);
	@Autowired
	private RedisUtil redisUtil;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String url = req.getServletPath();
		String a = "login.html";
		String b = "imagecode/getCode";
		String c = "manager/login";
		logger.info("url=======" + url);
		if (url.contains(a) || url.contains(b) || url.contains(c) || url.contains(".css") || url.contains(".js")
				|| url.contains(".jpg") || url.contains(".ico") || url.contains(".png") || url.contains(".html")
				|| url.contains(".woff") || url.contains(".ttf")) {
			chain.doFilter(req, res);
			return;
		} else {
			// 判断用户是否登录
			Cookie cookie = CookiesUtil.getCookieByName(req, "managerInfo");
			if (cookie == null) {
				res.setStatus(888);
				//res.sendRedirect(req.getContextPath() + "/login.html");
				return;
			}
			String key = cookie.getValue();
			if(key == null) {
				res.setStatus(888);
				//res.sendRedirect(req.getContextPath() + "/login.html");
				return;
			}
			String managerInfo = (String) redisUtil.get(RedisKeyEnum.MANAGER_INFO.getKey() + key);
			// 讲用户的cookie时间和redis时间从现在开始延长半小时
			if (managerInfo != null) {
				CookiesUtil.setCookie(res, "managerInfo", key, 60 * 30);
				redisUtil.set(RedisKeyEnum.MANAGER_INFO.getKey() + managerInfo, managerInfo, 60 * 30);
			} else {// 重定向到登录页
				res.setStatus(888);
				//res.sendRedirect(req.getContextPath() + "/login.html");
				return;
			}
			chain.doFilter(req, res);
		}
	}

}
